<?php
/*
 * @FilePath: Banners.php
 * @Author: 谭贤伟
 * @Date: 2023-03-31 16:59:17
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-04-07 19:22:42
 * @Descripttion: 
 */

declare(strict_types=1);

namespace app\api\controller;

use app\api\exception\ParamException;
use app\api\model\SupplyBanner;
use app\api\service\ApiResponse;
use app\api\validate\Banners as ValidateBanners;
use app\BaseController;
use think\facade\Cache;
use think\Request;

class Banners extends BaseController
{
    /**
     * @Author: 谭贤伟
     * @brief:  横幅广告
     * @return \think\Response
     */
    public function index()
    {
        $validate = new ValidateBanners;
        $result =  $validate->check([
            'limit'  => $this->request->get('limit'),
        ]);
        if ( !$result ) {
            throw new ParamException(400, $validate->getError());
        }
        if ( !Cache::has('banner') ) {
            if (!SupplyBanner::where('status', 1)->find()) {
                throw new ParamException(404);
            }
            $banner = SupplyBanner::where('status', 1)
                ->limit(intval($this->request->get('limit')))
                ->select();
            Cache::set('banner', $banner, mt_rand(1800, 3600));
            return ApiResponse::success(Cache::get('banner'));
        }
        return ApiResponse::success(Cache::get('banner'));
    }
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
